package sitonya.entity.roles

import com.icecreamqaq.yudb.jpa.JPADao
import onedice.utils.ToPlatFormId
import org.hibernate.Hibernate
import org.hibernate.annotations.CacheConcurrencyStrategy
import sitonya.concat.PLATFORM_KEY
import sitonya.entity.roles.idal.IRole
import sitonya.entity.roles.idal.RoleType
import javax.persistence.*
import javax.validation.constraints.NotNull

interface ICocRole : JPADao<CocRole, Long> {
    fun findById(
        id: Long = 0,
        name: String = ""
    ): CocRole? {
        val platformUserId = ToPlatFormId.toPlatformId(id, PLATFORM_KEY)
        return search("from CocRole where platformUserId=?0 and name=?1", platformUserId, name)
    }
}

@Entity
@Table(
    name = "Coc",
    catalog = "roles",
    uniqueConstraints = [UniqueConstraint(name="indexCocRole", columnNames = ["name","platformUserId"])]
)
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE, region = "system")
data class CocRole(
    @Id
    @GeneratedValue
    @Column(name = "oid")
    var oid: Long? = null,
    @NotNull
    @Column(name = "id")
    override var id: Long = 0,
    @NotNull
    @Column(name = "name")
    override var name: String = "",
    @NotNull
    @Column(name = "type")
    override var type: RoleType = RoleType.Coc,
    @NotNull
    @Column(name = "roleProp")
    @ElementCollection
    @CollectionTable(name = "CocRoleProp")
    @MapKeyColumn(name = "roleProp")
    override var roleProp: MutableMap<String, String> = mutableMapOf(),
    @NotNull
    @Column(name = "otherProp")
    @ElementCollection
    @CollectionTable(name = "CocOtherProp")
    @MapKeyColumn(name = "otherProp")
    override var otherProp: MutableMap<String, String> = mutableMapOf(),
    @NotNull
    @Column(name = "platformUserId")
    var platformUserId: String = ToPlatFormId.toPlatformId(id, PLATFORM_KEY),
) : IRole {
    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (other == null || Hibernate.getClass(this) != Hibernate.getClass(other)) return false
        other as CocRole

        return oid != null && oid == other.oid
    }

    override fun hashCode(): Int = javaClass.hashCode()

    @Override
    override fun toString(): String {
        return this::class.simpleName + "(name = $name , platformUserId = $platformUserId )"
    }
}